package com.wngbms.netty.seatdemo.service;

import com.alibaba.fastjson.JSON;
import com.wngbms.netty.seatdemo.bean.SeatEvent;
import com.wngbms.netty.seatdemo.comm.*;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatOutMessage;
import com.wngbms.netty.seatdemo.server.SeatBizHandler;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class EventHandler implements SeatTypeHandler {
    public static final CmdType CMD_TYPE = CmdType.EVENT;

    @Override
    public void handleOutbound(String userId) {
        log.info("推送事件信息:{}", userId);

        SeatEvent event = findEvent();
        byte[] bodyBytes = JSON.toJSONString(event).getBytes(StandardCharsets.UTF_8);
        BaseHeader baseHeader = BaseHeader.build(MagicVersion.V1,
                CMD_TYPE, BodyType.JSON,
                EncryptionType.NON, ReqOrResp.REQ,
                bodyBytes.length);

        SeatOutMessage seatOutMessage = new SeatOutMessage();
        seatOutMessage.setBaseHeader(baseHeader);
        seatOutMessage.setBody(bodyBytes);

        Channel channel = SeatBizHandler.USER_CHANNEL_MAP.get(userId);
        channel.writeAndFlush(seatOutMessage);
    }

    public SeatEvent findEvent() {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        SeatEvent seatEvent = new SeatEvent();
        seatEvent.setEventId(id);
        seatEvent.setEventTime(new Date());
        seatEvent.setMediaId("0_default_p12345");
        seatEvent.setSubsystemCode("p80033443");
        return seatEvent;
    }
}
